package org.example.androidMDSintegration;

/** ExampleActivity.java
 * Version 1.3; 18/03/14
 * This class demonstrates the use of the SanaClientLibrary to upload data to OpenMRS via
 * the Sana Mobile Dispatch Server. 
 * 
 *  Arvind Raghu
 *  Send in your comments or feedback to arvind.raghu@eng.ox.ac.uk
 * 
 *  -------Upload Preamble-----
  1)Retrieve your data (for instance, from sqlite database) 

  2)check connectivity - if good, resume. Otherwise - stay put in the local db.

  3)define manadtory variables including Patient ID, Name, Gender, DOB
  
  4)define other observations using the two HashMaps provided. One stores
  <Concept, Question> while the other stores <Concept, ObservationAnswer>

  5)Build the JSON string after setting a suitable encounter name
  
  6)Check server setup especially the username, password and DispatchServerURL

  7)Use postResonses. Receive uploaded confirmation

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


import java.io.IOException;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;

import com.example.isanatestuploading.net.Connectivity;
import com.example.isanatestuploading.net.RegisterPatient;
import com.example.isanatestuploading.net.SanaConstants;
import com.example.isanatestuploading.net.UploadActivity;

public class ExampleActivity extends Activity {
	private boolean isConnectivityGoodEnough;
	private String JsonString = "";
	int count = 500;
	HashMap<String, String> conceptsQuestionsMap;// concept-key; question-value
	HashMap<String, String> conceptsAnswersMap; // concept-key; observation's
												// answer- value

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		doUpload();
	}

	private void doUpload() {
		
		// check connectivity - if good, resume. Otherwise - stay put in the
		// local db.
		isConnectivityGoodEnough = Connectivity.isConnected(this);

		if (!(isConnectivityGoodEnough)) {
			Log.e(SanaConstants.TAG,
					"No Connection. Save to DB for upload at a later stage");
		} else {
			/* Upload to OpenMRS using Sana mds */
			RegisterPatient rp = new RegisterPatient();

			// mandatory observations
			rp.setPatientId("1812149");
			rp.setPatientFirstName("F6name-test");
			rp.setPatientLastName("L6name-test");
			rp.setPatientGender("Female");
			rp.setPatientBirthdateDay("10");
			rp.setPatientBirthdateMonth("11");
			rp.setPatientBirthdateYear("1956");

			// additional observations
			conceptsQuestionsMap = new HashMap<String, String>();
			conceptsQuestionsMap.put("USER ID", "Enter the user ID:");
			conceptsQuestionsMap.put("DATENTIME", "TimeStamp:");
			conceptsQuestionsMap.put("PH_CVD","Past History of CVD:");
			
			conceptsAnswersMap = new HashMap<String, String>();
			conceptsAnswersMap.put("USER ID", "179881");
			conceptsAnswersMap.put("DATENTIME", "26/8/13 18:55:16");
			conceptsAnswersMap.put("PH_CVD", "Nope");
			
			rp.setConceptsQuestions(conceptsQuestionsMap);
			rp.setConceptsObsAns(conceptsAnswersMap);

			JsonString = UploadActivity.buildJSONString("testUpload", rp);
			new UploadtoEMR().execute();
			Log.e(SanaConstants.TAG, "Started Upload Process");
		}

	}

	public class UploadtoEMR extends AsyncTask<Void, Void, Boolean> {

		private final ProgressDialog dialog = new ProgressDialog(
				ExampleActivity.this);

		// can use UI thread here
		@Override
		protected void onPreExecute() {
			// convert to JSON - here we have a sample JSON string

			SanaConstants.setUserName("guest");
			SanaConstants.setPassword("Sanamobile1");
			SanaConstants.setDispatchServerURL("demo.sana.csail.mit.edu");
			//SanaConstants.setPortNumber(443);
			SanaConstants.setPhoneNumber("555555");
		}

		@Override
		protected Boolean doInBackground(Void... arg0) {
			// can pass the context and JSON string for the sana MDS procedure
			// to upload
			boolean isCredentialOK = false;
			try {
				isCredentialOK = UploadActivity
						.validateCredentials(ExampleActivity.this);
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (isCredentialOK) {
				UploadActivity.postResponses(ExampleActivity.this, JsonString);
			}
			return null;
		}

		// can use UI thread here
		@Override
		protected void onPostExecute(final Boolean success) {
			if (dialog.isShowing()) {
				dialog.dismiss();
			}

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
